package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import pojo.User;
import service.UserService;

import javax.management.modelmbean.ModelMBeanInfo;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @RequestMapping("/toadd")
    public String toAdd(){
        return "user/add";
    }

    @RequestMapping("/login")
    public String login(User user)
    {
        boolean flag = userService.login(user);
        if(flag) {
            return "index";
        }
        else {
            return "login";
        }
    }

    @RequestMapping("/list")
    public String findAll(Model model)
    {
        List<User> users = userService.findAll(null, 0, 10);
        model.addAttribute("users",users);
        return "user/list";
    }

    @RequestMapping("/addSave")
    public String addUser(User user)
    {
        int result = userService.addUser(user);
            return "redirect:/user/list";
    }

    @RequestMapping("/delete/{id}")
    public String  deleteUser(@PathVariable("id") int id)
    {
        userService.deleteUser(id);
        return "redirect:/user/list";
    }

    @RequestMapping("/toupdate/{id}")
    public String toUpdateUser(@PathVariable("id") int id, Model model)
    {
        User user = userService.findUserById(id);
        model.addAttribute("user",user);
        return "user/update";
    }

    @RequestMapping("/update")
    public String UpdateUser(User user)
    {
        userService.updateUser(user);
        return "redirect:/user/list";
    }


}
